package scatter.userpost.rest.validate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import scatter.common.rest.service.IAddServiceListener;
import scatter.common.rest.service.IUpdateServiceListener;
import scatter.dept.pojo.po.Dept;
import scatter.dept.rest.service.IDeptService;
import scatter.job.pojo.po.Job;
import scatter.job.rest.service.IJobService;
import scatter.post.pojo.po.Post;
import scatter.post.rest.service.IPostService;
import scatter.userpost.pojo.form.UserPostAddForm;
import scatter.userpost.pojo.form.UserPostUpdateForm;
import scatter.userpost.pojo.po.UserPost;

/**
 * Created by yangwei
 * Created at 2021/3/30 13:27
 */
@Component
public class PostFormValidateListenerImpl implements IAddServiceListener<UserPost, UserPostAddForm>, IUpdateServiceListener<UserPost, UserPostUpdateForm> {

    @Autowired
    private IDeptService iDeptService;
    @Autowired
    private IPostService iPostService;
    @Autowired
    private IJobService iJobService;

    @Override
    public void preAdd(UserPostAddForm userPostAddForm, UserPost userPost) {
        validateComp(userPostAddForm.getCompId(), userPostAddForm.getDeptId());
        validateDept(userPostAddForm.getDeptId(), userPostAddForm.getPostId(), userPostAddForm.getJobId());
    }

    @Override
    public void preUpdate(UserPostUpdateForm userPostUpdateForm, UserPost userPost) {
        validateComp(userPostUpdateForm.getCompId(), userPostUpdateForm.getDeptId());
        validateDept(userPostUpdateForm.getDeptId(), userPostUpdateForm.getPostId(), userPostUpdateForm.getJobId());
    }

    /**
     * 公司验证
     * @param compId
     * @param deptId
     */
    private void validateComp(String compId,String deptId) {
        Dept byId = iDeptService.getById(deptId);
        Assert.isTrue(compId.equals(byId.getCompId()),"部门所属公司和录入公司不匹配");

    }

    /**
     * 部门验证
     * @param deptId
     * @param postId
     */
    private void validateDept(String deptId,String postId,String jobId) {

        Post byId = iPostService.getById(postId);
        if (!byId.getIsPublic()) {
            Assert.isTrue(deptId.equals(byId.getDeptId()),"岗位所属部门和录入部门不匹配");
        }

        Job byId1 = iJobService.getById(jobId);
        if (!byId1.getIsPublic()) {
            Assert.isTrue(deptId.equals(byId1.getDeptId()),"职务所属部门和录入部门不匹配");
        }
    }
}
